/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package zombiedefense.sprites;

import java.awt.Image;
import java.util.ArrayList;

/**
 *
 * @author Laptop2010
 */
public class Animation implements Cloneable{
    private Frame current;
    private int currentindex = 0;
    private ArrayList<Frame> frames;
    private boolean loop = true;

    private long timeSinceLastChange = 0;
    private long totaltime = 0;

    public Animation(){
	frames = new ArrayList<Frame>();
    }

    //add an image with a time to display
    public void addFrame(Image img, long time){
	Frame newframe = new Frame(img,time);

	frames.add(newframe);
	totaltime += time;
    }


    /**
     * Advance the animation if necessary and report if
     * update took place.
     * @param elapsedTime
     */
    public boolean update(long elapsedTime){
	if(frames.size() > 0){
	    if(current == null) current = frames.get(currentindex);

	    if(timeSinceLastChange >= current.time){
		currentindex = (loop)?(currentindex + 1) % frames.size():(currentindex == frames.size() - 1)?currentindex:currentindex + 1;
		current = frames.get(currentindex);

		timeSinceLastChange = 0;

		return true;
	    }else{
		timeSinceLastChange += elapsedTime;

		return false;
	    }
	}

	return false;
    }

    //get the current image
    public Image getCurrent(){
	if(current == null){
	    current = frames.get(currentindex);
	}
	return current.image;
    }

    //get the width of the current image
    public int getWidth(){
	Image current = getCurrent();
	if(current != null){
	    return current.getWidth(null);
	}else return -1;
    }

    //get the height of the current image
    public int getHeight(){
	Image current = getCurrent();
	if(current != null){
	    return current.getHeight(null);
	}else return -1;
    }

    public Object clone(){
	try{
	    return super.clone();
	}catch(Exception e){
	    e.printStackTrace();
	}

	return null;
    }

    public void setLoop(boolean loop){
	this.loop = loop;
    }

    /**
     * Returns the total length of the animation.
     * @return
     */
    public long getTotalTime(){
	return totaltime;
    }

    /**
     * Sets the current index to 0 and resets the animation timer.
     * Should be called right before the animation is to resume.
     */
    public void reset(){
	currentindex = 0;
	timeSinceLastChange = System.currentTimeMillis();
    }

    //one frame of the animation
    private class Frame{
	public long time;
	public Image image;

	public Frame(Image img, long time){
	    this.image = img;
	    this.time = time;
	}
    }
}
